package com.hiultra.video.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageInfo;
import com.hiultra.common.core.controller.BaseController;
import com.hiultra.common.core.domain.AjaxResult;
import com.hiultra.video.bean.*;
import com.hiultra.video.service.IVideoManagerStorage;
import com.hiultra.video.util.WVPNetUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.apache.ibatis.annotations.Options;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/videoMonitor/device")
public class DeviceController extends BaseController {
    private static String DEVICE_LIST_URL = "/api/device/query/devices";
    @Autowired
    WVPNetUtil wvpNetUtil;

    @Autowired
    private IVideoManagerStorage storager;

    /**
     * 获取所有设备列表
     *
     * @return
     */
    @GetMapping(value = "/list")
    public AjaxResult list() {
        if (logger.isDebugEnabled()) {
            logger.debug("查询所有视频设备API调用");
        }
        try {
            List<Device> devices = wvpNetUtil.getDevices();
            return AjaxResult.success(devices);
        } catch (Exception exception) {
            return AjaxResult.error();
        }
    }

    /**
     * 获取设备的通道列表
     *
     * @return
     */
    @GetMapping(value = "/{deviceId}/channels")
    public AjaxResult channelList(@PathVariable String deviceId) {
        if (logger.isDebugEnabled()) {
            logger.debug("查询设备所有通道API调用");
        }
        try {
            List<DeviceChannel> channels = wvpNetUtil.getChannels(deviceId);
            return AjaxResult.success(channels);
        } catch (Exception exception) {
            return AjaxResult.error();
        }
    }

    @Operation(summary = "开始点播")
    @Parameter(name = "deviceId", description = "设备国标编号", required = true)
    @Parameter(name = "channelId", description = "通道国标编号", required = true)
    @GetMapping("/start/{deviceId}/{channelId}")
    public AjaxResult play(HttpServletRequest request, @PathVariable String deviceId,
                           @PathVariable String channelId) {
        logger.info("[开始点播] deviceId：{}, channelId：{}, ", deviceId, channelId);
        try {
            StreamContent streamContent = wvpNetUtil.play(deviceId, channelId);
            return AjaxResult.success(streamContent);
        } catch (Exception exception) {
            logger.error(exception.getMessage());
            return AjaxResult.error();
        }
    }

    @Operation(summary = "停止点播")
    @Parameter(name = "deviceId", description = "设备国标编号", required = true)
    @Parameter(name = "channelId", description = "通道国标编号", required = true)
    @GetMapping("/stop/{deviceId}/{channelId}")
    public AjaxResult stop(HttpServletRequest request, @PathVariable String deviceId,
                           @PathVariable String channelId) {
        logger.info("[停止点播] deviceId：{}, channelId：{}, ", deviceId, channelId);
        try {

            JSONObject stop = wvpNetUtil.stop(deviceId, channelId);
            return AjaxResult.success(stop);
        } catch (Exception exception) {
            logger.error(exception.getMessage());
            return AjaxResult.error();
        }
    }

    @Operation(summary = "查询回放记录")
    @Parameter(name = "deviceId", description = "设备国标编号", required = true)
    @Parameter(name = "channelId", description = "通道国标编号", required = true)
    @GetMapping("/record/query/{deviceId}/{channelId}")
    public AjaxResult recordQuery(HttpServletRequest request, @PathVariable String deviceId,
                                  @PathVariable String channelId, String startTime, String endTime) {
        logger.info("[查询回放] deviceId：{}, channelId：{}, ", deviceId, channelId);
        try {
            DeviceRecord deviceRecord = wvpNetUtil.recordQuery(deviceId, channelId, startTime, endTime);
            return AjaxResult.success(deviceRecord);
        } catch (Exception exception) {
            logger.error(exception.getMessage());
            return AjaxResult.error();
        }
    }

    @Operation(summary = "播放回访")
    @Parameter(name = "deviceId", description = "设备国标编号", required = true)
    @Parameter(name = "channelId", description = "通道国标编号", required = true)
    @GetMapping("/record/start/{deviceId}/{channelId}")
    public AjaxResult recordStart(HttpServletRequest request, @PathVariable String deviceId,
                                  @PathVariable String channelId, String startTime, String endTime) {
        logger.info("[开始播放回放] deviceId：{}, channelId：{}, ", deviceId, channelId);
        try {
            if(StrUtil.isNotBlank(startTime) && startTime.contains("%20")){
                startTime = startTime.split("%20")[0];
            }
            if(StrUtil.isNotBlank(endTime) && endTime.contains("%20")){
                endTime = endTime.split("%20")[0];
            }
            VideoRecord videoRecord = wvpNetUtil.recordStart(deviceId, channelId, startTime, endTime);
            return AjaxResult.success(videoRecord);
        } catch (Exception exception) {
            logger.error(exception.getMessage());
            return AjaxResult.error();
        }
    }

    @Operation(summary = "停止播放回放")
    @Parameter(name = "deviceId", description = "设备国标编号", required = true)
    @Parameter(name = "channelId", description = "通道国标编号", required = true)
    @GetMapping("/record/stop/{deviceId}/{channelId}/{stream}")
    public AjaxResult recordStop(HttpServletRequest request, @PathVariable String deviceId, @PathVariable String channelId, @PathVariable String stream) {
        logger.info("[停止播放回放] deviceId：{}, channelId：{}, ", deviceId, channelId);
        try {
            JSONObject jsonObject = wvpNetUtil.recordStop(deviceId, channelId, stream);
            return AjaxResult.success(jsonObject);
        } catch (Exception exception) {
            logger.error(exception.getMessage());
            return AjaxResult.error();
        }
    }

    /**
     * 分页查询国标设备
     * @param page 当前页
     * @param count 每页查询数量
     * @return 分页国标列表
     */
    @Operation(summary = "分页查询国标设备")
    @Parameter(name = "page", description = "当前页", required = true)
    @Parameter(name = "count", description = "每页查询数量", required = true)
    @GetMapping("/devices")
    @Options()
    public PageInfo<Device> devices(int page, int count){
//		if (page == null) page = 0;
//		if (count == null) count = 20;
        return storager.queryVideoDeviceList(page, count,null);
    }
}
